{
 "cells": [
  {
   "metadata": {},
   "cell_type": "markdown",
   "source": "### 分组运算",
   "id": "91057c4ceb32965a"
  },
  {
   "metadata": {
    "ExecuteTime": {
     "end_time": "2025-01-19T12:03:50.595648Z",
     "start_time": "2025-01-19T12:03:50.126201Z"
    }
   },
   "cell_type": "code",
   "source": [
    "import numpy as np\n",
    "import pandas as pd\n",
    "\n",
    "#分组后给名称加前缀\n",
    "dict_obj = {'key1' : ['a', 'b', 'a', 'b',\n",
    "                      'a', 'b', 'a', 'a'],\n",
    "            'key2' : ['one', 'one', 'two', 'three',\n",
    "                      'two', 'two', 'one', 'three'],\n",
    "            'data1': np.random.randint(1, 10, 8),\n",
    "            'data2': np.random.randint(1, 10, 8)}\n",
    "df_obj = pd.DataFrame(dict_obj)\n",
    "print(df_obj)\n",
    "print('-'*50)\n",
    "\n",
    "# 按key1分组后，计算data1，data2的统计信息并附加到原始表格中，并添加表头前缀\n",
    "# numeric_only=True表示只计算数值型数据; add_prefix添加表头前缀\n",
    "k1_sum = df_obj.groupby('key1').mean(numeric_only=True).add_prefix('mean_')\n",
    "print(k1_sum)"
   ],
   "id": "187619744f140053",
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "  key1   key2  data1  data2\n",
      "0    a    one      8      4\n",
      "1    b    one      5      9\n",
      "2    a    two      6      3\n",
      "3    b  three      5      8\n",
      "4    a    two      7      6\n",
      "5    b    two      4      7\n",
      "6    a    one      5      4\n",
      "7    a  three      9      1\n",
      "--------------------------------------------------\n",
      "      mean_data1  mean_data2\n",
      "key1                        \n",
      "a       7.000000         3.6\n",
      "b       4.666667         8.0\n"
     ]
    }
   ],
   "execution_count": 1
  },
  {
   "metadata": {
    "ExecuteTime": {
     "end_time": "2025-01-17T11:48:40.580900Z",
     "start_time": "2025-01-17T11:48:40.571439Z"
    }
   },
   "cell_type": "code",
   "source": [
    "# 方法2，使用transform，分组后计算结果和原本的df保持一致\n",
    "# 存在非数值型列，先把数值型挑出来\n",
    "k1_sum_tf = df_obj.loc[:, ['key1','data1', 'data2']].groupby('key1').transform('mean').add_prefix('mean_')\n",
    "print(k1_sum_tf)\n",
    "# 将计算得到的平均值数据框k1_sum_tf的列附加到原始数据框 df_obj 中。\n",
    "df_obj[k1_sum_tf.columns] = k1_sum_tf\n",
    "print(df_obj)"
   ],
   "id": "11d0827716f36c2e",
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "   mean_data1  mean_data2\n",
      "0         5.4         5.6\n",
      "1         3.0         6.0\n",
      "2         5.4         5.6\n",
      "3         3.0         6.0\n",
      "4         5.4         5.6\n",
      "5         3.0         6.0\n",
      "6         5.4         5.6\n",
      "7         5.4         5.6\n",
      "  key1   key2  data1  data2  mean_data1  mean_data2\n",
      "0    a    one      4      9         5.4         5.6\n",
      "1    b    one      4      7         3.0         6.0\n",
      "2    a    two      8      6         5.4         5.6\n",
      "3    b  three      3      8         3.0         6.0\n",
      "4    a    two      2      8         5.4         5.6\n",
      "5    b    two      2      3         3.0         6.0\n",
      "6    a    one      5      1         5.4         5.6\n",
      "7    a  three      8      4         5.4         5.6\n"
     ]
    }
   ],
   "execution_count": 13
  },
  {
   "metadata": {
    "ExecuteTime": {
     "end_time": "2025-01-17T11:48:41.290353Z",
     "start_time": "2025-01-17T11:48:41.287781Z"
    }
   },
   "cell_type": "code",
   "source": "del df_obj['key2']",
   "id": "409679c4e377dd70",
   "outputs": [],
   "execution_count": 14
  },
  {
   "metadata": {
    "ExecuteTime": {
     "end_time": "2025-01-17T11:48:46.070171Z",
     "start_time": "2025-01-17T11:48:46.066542Z"
    }
   },
   "cell_type": "code",
   "source": [
    "del df_obj['mean_data1']\n",
    "del df_obj['mean_data2']\n",
    "print(df_obj)"
   ],
   "id": "b0955bf51a4e1937",
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "  key1  data1  data2\n",
      "0    a      4      9\n",
      "1    b      4      7\n",
      "2    a      8      6\n",
      "3    b      3      8\n",
      "4    a      2      8\n",
      "5    b      2      3\n",
      "6    a      5      1\n",
      "7    a      8      4\n"
     ]
    }
   ],
   "execution_count": 16
  },
  {
   "metadata": {
    "ExecuteTime": {
     "end_time": "2025-01-17T11:19:54.901186Z",
     "start_time": "2025-01-17T11:19:54.896590Z"
    }
   },
   "cell_type": "code",
   "source": "df_obj.groupby('key1').transform('mean').add_prefix('mean_')  # 与原数据格式一致",
   "id": "c32d648f2bc5a651",
   "outputs": [
    {
     "data": {
      "text/plain": [
       "   mean_data1  mean_data2\n",
       "0         4.6         3.6\n",
       "1         5.0         2.0\n",
       "2         4.6         3.6\n",
       "3         5.0         2.0\n",
       "4         4.6         3.6\n",
       "5         5.0         2.0\n",
       "6         4.6         3.6\n",
       "7         4.6         3.6"
      ],
      "text/html": [
       "<div>\n",
       "<style scoped>\n",
       "    .dataframe tbody tr th:only-of-type {\n",
       "        vertical-align: middle;\n",
       "    }\n",
       "\n",
       "    .dataframe tbody tr th {\n",
       "        vertical-align: top;\n",
       "    }\n",
       "\n",
       "    .dataframe thead th {\n",
       "        text-align: right;\n",
       "    }\n",
       "</style>\n",
       "<table border=\"1\" class=\"dataframe\">\n",
       "  <thead>\n",
       "    <tr style=\"text-align: right;\">\n",
       "      <th></th>\n",
       "      <th>mean_data1</th>\n",
       "      <th>mean_data2</th>\n",
       "    </tr>\n",
       "  </thead>\n",
       "  <tbody>\n",
       "    <tr>\n",
       "      <th>0</th>\n",
       "      <td>4.6</td>\n",
       "      <td>3.6</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>1</th>\n",
       "      <td>5.0</td>\n",
       "      <td>2.0</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>2</th>\n",
       "      <td>4.6</td>\n",
       "      <td>3.6</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>3</th>\n",
       "      <td>5.0</td>\n",
       "      <td>2.0</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>4</th>\n",
       "      <td>4.6</td>\n",
       "      <td>3.6</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>5</th>\n",
       "      <td>5.0</td>\n",
       "      <td>2.0</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>6</th>\n",
       "      <td>4.6</td>\n",
       "      <td>3.6</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>7</th>\n",
       "      <td>4.6</td>\n",
       "      <td>3.6</td>\n",
       "    </tr>\n",
       "  </tbody>\n",
       "</table>\n",
       "</div>"
      ]
     },
     "execution_count": 15,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "execution_count": 15
  },
  {
   "metadata": {
    "ExecuteTime": {
     "end_time": "2025-01-17T11:20:21.392971Z",
     "start_time": "2025-01-17T11:20:21.385472Z"
    }
   },
   "cell_type": "code",
   "source": [
    "#实现a组和b组，谁比平均分高，谁比平均分低\n",
    "def diff_mean(s):\n",
    "    \"\"\"\n",
    "        返回数据与均值的差值，s传入的是某一个分组\n",
    "    \"\"\"\n",
    "    return s - s.mean()\n",
    "\n",
    "print(df_obj.groupby('key1').transform(diff_mean))\n",
    "df_obj"
   ],
   "id": "e940faac38b14fd3",
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "   data1  data2\n",
      "0    3.4   -2.6\n",
      "1   -4.0    2.0\n",
      "2   -0.6    1.4\n",
      "3    3.0   -1.0\n",
      "4   -2.6   -2.6\n",
      "5    1.0   -1.0\n",
      "6    1.4    3.4\n",
      "7   -1.6    0.4\n"
     ]
    },
    {
     "data": {
      "text/plain": [
       "  key1  data1  data2\n",
       "0    a      8      1\n",
       "1    b      1      4\n",
       "2    a      4      5\n",
       "3    b      8      1\n",
       "4    a      2      1\n",
       "5    b      6      1\n",
       "6    a      6      7\n",
       "7    a      3      4"
      ],
      "text/html": [
       "<div>\n",
       "<style scoped>\n",
       "    .dataframe tbody tr th:only-of-type {\n",
       "        vertical-align: middle;\n",
       "    }\n",
       "\n",
       "    .dataframe tbody tr th {\n",
       "        vertical-align: top;\n",
       "    }\n",
       "\n",
       "    .dataframe thead th {\n",
       "        text-align: right;\n",
       "    }\n",
       "</style>\n",
       "<table border=\"1\" class=\"dataframe\">\n",
       "  <thead>\n",
       "    <tr style=\"text-align: right;\">\n",
       "      <th></th>\n",
       "      <th>key1</th>\n",
       "      <th>data1</th>\n",
       "      <th>data2</th>\n",
       "    </tr>\n",
       "  </thead>\n",
       "  <tbody>\n",
       "    <tr>\n",
       "      <th>0</th>\n",
       "      <td>a</td>\n",
       "      <td>8</td>\n",
       "      <td>1</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>1</th>\n",
       "      <td>b</td>\n",
       "      <td>1</td>\n",
       "      <td>4</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>2</th>\n",
       "      <td>a</td>\n",
       "      <td>4</td>\n",
       "      <td>5</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>3</th>\n",
       "      <td>b</td>\n",
       "      <td>8</td>\n",
       "      <td>1</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>4</th>\n",
       "      <td>a</td>\n",
       "      <td>2</td>\n",
       "      <td>1</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>5</th>\n",
       "      <td>b</td>\n",
       "      <td>6</td>\n",
       "      <td>1</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>6</th>\n",
       "      <td>a</td>\n",
       "      <td>6</td>\n",
       "      <td>7</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>7</th>\n",
       "      <td>a</td>\n",
       "      <td>3</td>\n",
       "      <td>4</td>\n",
       "    </tr>\n",
       "  </tbody>\n",
       "</table>\n",
       "</div>"
      ]
     },
     "execution_count": 18,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "execution_count": 18
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 2
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython2",
   "version": "2.7.6"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
